<?php
/**
 * Created by PhpStorm.
 * User: jwb
 * Date: 2020/5/22
 * Time: 17:28
 */

namespace App\Repositories\Eloquent;

use Illuminate\Database\Eloquent\Model;

trait BaseRepository
{

    /**
     * @var Model|mixed
     */
    protected $model;

    /**
     * @param array $columns
     * @return mixed
     */
    public function all($columns = array('*'))
    {
        return $this->model->get($columns);
    }


    /**
     * @param int $perPage
     * @param array $columns
     * @return mixed
     */
    public function paginate($perPage = 15, $columns = array('*'))
    {
        return $this->model->paginate($perPage, $columns);
    }

    /**
     * @param array $data
     * @return mixed
     */
    public function create(array $data)
    {
        return $this->model->create($data);
    }

    /**
     * @param array $data
     * @param $id
     * @param string $attribute
     * @return mixed
     */
    public function update(array $data, $id, $attribute = 'id')
    {
        return $this->model->where($attribute, '=', $id)->update($data);
    }

    /**
     * @param $id
     * @return mixed
     */
    public function delete($id)
    {
        return $this->model->destroy($id);
    }

    /**
     * @param $id
     * @param array $columns
     * @return mixed
     */
    public function find($id, $columns = array('*'))
    {
        return $this->model->find($id, $columns);
    }

    public function findOrFail($id, $columns = array('*'))
    {
        return $this->model->findOrFail($id, $columns);
    }

    /**
     * @param $field
     * @param $value
     * @param array $columns
     * @return mixed
     */
    public function findBy($field, $value, $columns = array('*'))
    {
        return $this->model->where($field, '=', $value)->first($columns);
    }

    public function pluck($column, $key = null)
    {
        return $this->model->pluck($column, $key);
    }

    public function getBy($where, $columns = array('*'))
    {
        return $this->model->where($where)->get($columns);
    }

    public function pluckWhereIn($field, array $values, $name, $key = null)
    {
        return $this->model->whereIn($field, $values)->pluck($name, $key);
    }

    public function updateOrCreate(array $attributes, array $values = [])
    {
        $this->model->newQuery()->updateOrCreate($attributes, $values);
    }

    public function firstOrCreate(array $attributes, array $values = [])
    {
        $this->model->newQuery()->firstOrCreate($attributes, $values);
    }
}
